<?php

namespace app\common\service;

use app\common\exception\BusinessException;
use think\facade\Cache;
use think\facade\Config;

class MailService
{
    /**
     * sendPrefix
     * @var string
     */
    private $sendPrefix = 'mcp.cache_key.mail_code';

    /**
     * 发送验证码
     * @param string $email
     * @param string $tpl_id
     * @throws
     */
    public function sendCode(string $email, string $tpl_id)
    {
        //get_config
        $prefix = Config::get($this->sendPrefix);
        $cacheKey = $prefix . $email;

        //build_code
        $verifyCode = rand(100000, 999999);

        //build_message
        $config = Config::get($tpl_id);
        $title = $config['title'];
        $content = $config['content'];
        $content = sprintf($content, $verifyCode);

        //send_email
        send_email($email, $title, $content);
        if (!Cache::set($cacheKey, $verifyCode, 3600))
        {
            throw new BusinessException('保存验证码失败');
        }
    }

    /**
     * 校验验证码
     * @param string $email
     * @param string $code
     * @return bool
     */
    public function checkCode(string $email, string $code): bool
    {
        //get_config
        $prefix = Config::get($this->sendPrefix);
        $cacheKey = $prefix . $email;
        $realCode = Cache::get($cacheKey, '');
        if ($code == $realCode)
        {
            Cache::set($cacheKey, '', 0);
            return true;
        }
        else
        {
            return false;
        }
    }
}